package sunyu.toolkit.core;

import org.nustaq.serialization.FSTObjectInput;
import org.nustaq.serialization.FSTObjectOutput;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

/**
 * 序列化工具，使用fst实现
 *
 * @author 孙宇
 */
public class SerializerKit {

    /**
     * 序列化对象
     *
     * @param obj 对象
     * @return 字节数组
     */
    public static byte[] serialize(Object obj) {
        try (ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
             FSTObjectOutput fstOut = new FSTObjectOutput(bytesOut);) {
            fstOut.writeObject(obj);
            fstOut.flush();
            return bytesOut.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 反序列化对象
     *
     * @param bytes 字节数组
     * @return 对象
     */
    public static Object deserialize(byte[] bytes) {
        if (bytes == null || bytes.length == 0) {
            return null;
        }

        try (FSTObjectInput fstInput = new FSTObjectInput(new ByteArrayInputStream(bytes));) {
            return fstInput.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 反序列化对象
     *
     * @param bytes  字节数组
     * @param toType 序列化类型
     * @param <T>    泛型
     * @return 对象
     */
    public static <T> T deserialize(byte[] bytes, Class<T> toType) {
        return (T) deserialize(bytes);
    }

}
